package zd.cornermemory.fragment.graph;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import zd.cornermemory.App;
import zd.cornermemory.R;
import zd.cornermemory.db.Cj;
import zd.cornermemory.ui.GraphicActivity;
import zd.cornermemory.utils.Configs;
import zd.cornermemory.utils.Graph;

/**
 * Created by zhud on 2019/4/29.
 */

public class GraphFragment extends Fragment{

    private ImageView imageView;
    private int          currentPos;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_graphic, container, false);
        imageView = view.findViewById(R.id.imageView);
        GraphicActivity activity = (GraphicActivity) getActivity();
        currentPos = activity.getCurrentPos();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                drawGraph();
            }
        });
        return view;
    }


    private void drawGraph(){
        List<Cj> cjList = App.getInstance().getAllCjMap().get(currentPos);
        if (cjList == null) {
            cjList = new ArrayList<>();
        }
        Collections.sort(cjList, new Comparator<Cj>() {
            @Override
            public int compare(Cj cj, Cj t1) {
                return (int)(cj.getId()-t1.getId());
            }
        });
        Bitmap bm = Bitmap.createBitmap(Configs.width, (int)(Configs.height), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bm);
        Paint p = new Paint();
        p.setAntiAlias(true);
        Graph.drawGraph(Configs.width,Configs.height, p, c,cjList);
        imageView.setImageBitmap(bm);
    }
}
